package com.tanhua.server.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.server.pojo.User;
import com.tanhua.server.utils.UserThreadLocal;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author Au
 * @DATE 2020/11/24 19:04
 **/
@Service
public class QuanziMQService {

    private static final Logger LOGGER = LoggerFactory.getLogger(QuanziMQService.class);
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    /**
     * 发布动态消息
     *
     * @param publishId
     * @return
     */
    public void sendSavePublishMsg(String publishId) {
        this.sendMsg(1, publishId);
    }

    /**
     * 浏览动态消息
     *
     * @param publishId
     * @return
     */
    public void sendSaveQueryPublishMsg(String publishId) {
        this.sendMsg(2, publishId);
    }

    /**
     * 点赞动态消息
     *
     * @param publishId
     * @return
     */
    public void sendSaveLikePublishMsg(String publishId) {
        this.sendMsg(3, publishId);
    }

    /**
     * 取消点赞动态消息
     *
     * @param publishId
     * @return
     */
    public void sendSaveDisLikePublishMsg(String publishId) {
        this.sendMsg(6, publishId);
    }

    /**
     * 喜欢动态消息
     *
     * @param publishId
     * @return
     */
    public void sendSaveLovePublishMsg(String publishId) {
        this.sendMsg(4, publishId);
    }

    /**
     * 取消喜欢动态消息
     *
     * @param publishId
     * @return
     */
    public void sendSaveDisLovePublishMsg(String publishId) {
        this.sendMsg(7, publishId);
    }

    /**
     * 评论动态消息
     *
     * @param publishId
     * @return
     */
    public void sendSaveCommentPublishMsg(String publishId) {
        this.sendMsg(5, publishId);
    }


    public void sendMsg(Integer type, String publishId) {
        try {
            User user = UserThreadLocal.get();

            Map<String, Object> map = new HashMap();


            Publish publish = quanZiApi.queryPublishById(publishId);

            map.put("type", type);
            map.put("publishId", publishId);
            map.put("date", System.currentTimeMillis());
            map.put("userId", user.getId());
            map.put("pid", publish.getPid());

            rocketMQTemplate.convertAndSend("tanhua-quanzi", map);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("圈子消息发送失败! type= " + type + ", " + "publishId" + publishId, e);
        }
    }
}
